#!/usr/bin/python
# -*- coding:utf-8 -*-
#
# HappyPlane
#
# Created by meiguizhinian on 2019/1/2
# Copyright © 2019 lixiaolong. All rights reserved.

import os
import sys
import chardet


class Update:
	root = None
	ENCODE_TABLE = {
		"UTF-8": ["plist", "txt", "csv", "js", "json", "atlas"],
		"UTF-8-SIG" : ["h", "c","hpp", "cpp"],
	}

	# 文件编码检查
	def encode(self, path):
		for k in self.ENCODE_TABLE:
			path = os.path.join(self.root, path)
			files = self.walkfiles(path, self.ENCODE_TABLE[k])
			if not files:
				continue
				pass
			for file in files:
				data = self.read(file)
				info = chardet.detect(data)
				if info["confidence"] > 0.7:
					encoding = info["encoding"].upper()
					if encoding == "ASCII" or encoding == k:
						continue
						pass
					if encoding == "ISO-8859-1":
						print("ISO-8859-1:",file)
						continue
						pass
				else:
					continue
					pass
				print("encode", file, info["encoding"], k)
				try:
					data = data.decode(info["encoding"]).encode(k)
				except UnicodeDecodeError:
					data = data.decode("GB18030").encode(k)
				except LookupError:
					data = data.decode("GB18030").encode(k)
					pass
				self.write(file, data)
				pass
			pass
		pass

	def read(self, path):
		f = open(path, 'rb')
		data = f.read()
		f.close()
		return data

	def write(self, path, data):
		f = open(path, 'wb')
		f.write(data)
		f.close()
		pass

	def walkfiles(self, path, endswith):
		array = []
		for (root, dirs, files) in os.walk(path):
			if os.path.basename(root).startswith('.'):
				continue
				pass
			for filename in files:
				if filename.startswith('.'):
					continue
				if endswith:
					if not self.endsinlist(filename, endswith):
						continue
						pass
					pass
				
				filepath = os.path.join(root, filename)
				array.append(filepath)
				pass
			pass
		return array
		pass

	def endsinlist(self, string, items):
		for item in items:
			if string.endswith(item):
				return True
			pass
		return False

	pass


if __name__ == '__main__':
	update = Update()
	update.root = os.getcwd()
	update.encode("script")
	pass
